<template>
  <view class="commodities">
    <view class="row b-b">
      <view>
        <text class="tit-text">选择一级分类</text>
      </view>
      <view class="flex" @tap="selectItem()">
        <text class="tit-text right-style">{{
          products.fist_category.name == ""
            ? "选择一级分类"
            : products.fist_category.name
        }}</text>
        <view class="border-right"> </view>
      </view>
    </view>
    <view class="row b-b">
      <text class="tit-text">商品标题</text>
      <input
        class="input"
        type="text"
        v-model="products.title"
        @blur="changeTitle"
        placeholder="请输入商品标题"
        placeholder-class="placeholder"
      />
    </view>
    <view v-for="(item, index) in products.spec" :key="index">
      <view class="row b-b">
        <text class="tit-text">规格{{ index + 1 }}</text>
        <input
          class="input"
          type="text"
          v-model="item.spec"
          @blur="changeFirstSpec($event, index)"
          placeholder="请输入商品规格"
          placeholder-class="placeholder"
        />
      </view>
      <view class="row b-b">
        <text class="tit-text" style="width: 70%"></text>
        ¥<input
          class="input"
          type="number"
          v-model="item.price"
          @blur="changeFirstPrice($event, index)"
          placeholder="请输入商品价格"
          maxlength="8"
          placeholder-class="placeholder"
        />
      </view>
    </view>
    <view class="row b-b" @tap="deleteProduct">
      <text
        class="tit-text"
        style="width: 100%; text-align: right; color: #f91c1c; font-size: 24upx"
        >删除规格</text
      >
    </view>
    <view class="row b-b" @tap="addProduct">
      <text
        class="tit-text"
        style="
          width: 100%;
          text-align: center;
          font-size: 28upx;
          font-weight: 500;
          color: #f91c1c;
        "
        >添加规格</text
      >
    </view>
    <view class="split-border"> </view>
    <view class="shop-detail">
      <view class="shop-title">商品详情</view>
      <textarea
        class="textarea"
        v-model="products.content"
        @blur="changeContent"
        placeholder="请输入商品详情"
        placeholder-style="font-size: 28upx;color: #999999;"
      ></textarea>
    </view>
    <view class="image-box-wrappers border-bottom">
      <view
        v-for="(item, index) in products.content_images"
        :key="index"
        class="image-item"
      >
        <image
          :src="btn_shanchu"
          class="delete-img"
          @tap="deleteImg(index, 'tupian')"
        ></image>
        <image :src="item.path" class="images"></image>
      </view>
      <view class="portrait-box" @tap="uploadImage('tubian')">
        <image class="portraits" :src="icon_shangchuan"></image>
      </view>
      <!-- <view class="portrait-box">
        <avatar
          canRotate="false"
          @upload="handleUploadFiles"
          :avatarSrc="icon_shangchuan"
          avatarStyle="width:116upx;height:116upx;border-radius:0;"
        >
        </avatar>
      </view> -->
    </view>
    <view class="image-box-wrappers">
      <view
        v-for="(item, index) in products.images"
        :key="index"
        class="image-item"
      >
        <image
          :src="btn_shanchu"
          class="delete-img"
          @tap="deleteImg(index, 'zhutu')"
        ></image>
        <image :src="item.path" class="image"></image>
      </view>
      <view class="portrait-box" @tap="uploadImage('zhutu')">
        <image class="portrait" :src="icon_zhutu"></image>
      </view>
      <!--非h5裁剪头像上传-->
      <!-- <view class="portrait-box">
        <avatar
          canRotate="false"
          selWidth="400upx"
          selHeight="400upx"
          @upload="handleUploadFile"
          :avatarSrc="icon_zhutu"
          avatarStyle="width: 160upx; height:160upx;border-radius:0;"
        >
        </avatar>
      </view> -->
    </view>
    <Popup
      v-if="firstList.length > 0"
      :level="'1'"
      :list="firstList"
      @closepop="closefirstListpop"
      ref="firstList"
    >
    </Popup>
    <!--加载动画-->
    <rfLoading isFullScreen :active="loading"></rfLoading>
  </view>
</template>
<script>
import Popup from "@/components/item-popup/index";
import { product, category } from "@/api/product";
import avatar from "@/components/rf-avatar/rf-avatar";
import { uploadImage } from "@/api/login";
export default {
  components: { avatar, Popup },
  data() {
    return {
      loading: false,
      shopDetail: "",
      title: "发布商品",
      business_id: "",
      specClass: "none",
      categoryId: null,
      icon_shangchuan: this.$mAssetsPath.icon_shangchuan,
      icon_zhutu: this.$mAssetsPath.icon_zhutu,
      nav_back: this.$mAssetsPath.nav_back,
      btn_shanchu: this.$mAssetsPath.btn_shanchu,
      profileInfo: {},
      products: {
        fist_category: {
          name: "",
          id: "",
        },
        category_id: null,
        title: "",
        spec: [
          {
            spec: null,
            price: null,
          },
        ],
        content: "",
        content_images: [],
        images: [],
      },
      firstList: [],
      reqBody: {},
    };
  },
  // 每次页面显示 执行该方法
  onLoad(option) {
    this.getCategoryList("1");
    if (option.id) {
      this.categoryId = option.id;
      this.title = "编辑商品";
      uni.setNavigationBarTitle({
        title: this.title,
      });
      this.initData(option.id);
    }
  },
  // #ifndef MP
  onNavigationBarButtonTap(e) {
    this.saveShop();
  },
  // #endif
  methods: {
    addProduct() {
      let spec = {
        spec: null,
        price: null,
      };
      this.products.spec.push(spec);
    },
    deleteProduct() {
      this.products.spec.splice(1);
    },
    changeTitle(e) {
      this.products.title = e.detail.value;
    },
    changeFirstSpec(e, index) {
      console.log(e, index);
      this.products.spec[index].spec = e.detail.value;
    },
    changeFirstPrice(e, index) {
      this.products.spec[index].price = e.detail.value;
    },
    changeContent(e) {
      this.products.content = e.detail.value;
    },
    closefirstListpop(pruduct) {
      if (pruduct) {
        this.products.fist_category.name = pruduct.name;
        this.products.fist_category.id = Number(pruduct.id);
        this.products.category_id = Number(pruduct.id);
      }
    },
    // 上传头像
    uploadImage(type) {
      // 从相册选择图片
      const _this = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: function (res) {
          if (type == "zhutu") {
            _this.handleUploadFile(res.tempFilePaths);
          } else {
            _this.handleUploadFiles(res.tempFilePaths);
          }
        },
      });
    },
    handleUploadFiles(data) {
      const _this = this;
      const filePath = data.path || data[0];
      _this.$http
        .upload(uploadImage, {
          filePath,
          name: "file",
        })
        .then((r) => {
          let image = {
            path: r.data,
          };
          this.products.content_images.push(image);
        });
    },
    // 上传头像
    handleUploadFile(data) {
      const _this = this;
      const filePath = data.path || data[0];
      _this.$http
        .upload(uploadImage, {
          filePath,
          name: "file",
        })
        .then((r) => {
          let image = {
            path: r.data,
          };
          this.products.images.push(image);
        });
    },
    //显示模态框
    selectItem() {
      let currentIndex = 0
      if(this.products.fist_category.id){
        currentIndex =this.firstList.findIndex((d)=>{
           return this.products.fist_category.id ===d.id
        })
      }
      this.$refs.firstList.showPopup(currentIndex);
    },
    //删除图片
    deleteImg(index, type) {
      if (type === "zhutu") {
        this.products.images.splice(index, 1);
      } else {
        this.products.content_images.splice(index, 1);
      }
    },
    navBack() {
      this.$mRouter.back();
    },
    async getCategoryList(level) {
      await this.$http
        .get(category, {
          level: level,
        })
        .then((res) => {
          this.firstList = res.data;
        })
        .catch(() => {});
    },
    async saveShop() {
      this.reqBody["category_id"] = this.products["category_id"];
      this.reqBody["title"] = this.products["title"];
      const cheRes = this.$mGraceChecker.check(
        this.reqBody,
        this.$mFormRule.releasecommodities
      );
      if (!cheRes) {
        this.$mHelper.toast(this.$mGraceChecker.error);
        return;
      }

      if (!this.products.spec[0].price) {
        this.$mHelper.toast("请输入商品价格");
        return;
      }
      if (this.products.images.length === 0) {
        this.$mHelper.toast("请至少上传一张商品图片");
        return;
      }
      if (this.title == "发布商品") {
        this.releaseCommodities();
      } else {
        this.editCommodities();
      }
    },
    getParams(param) {
      if (!param.content) {
        delete param.content;
      }
      if (!param.content_images || param.content_images.length === 0) {
        delete param.content_images;
      }
      return param;
    },
    //编辑商品
    async editCommodities() {
      let param = this.getParams(this.products);
      param = Object.assign(param, category_id);
      await this.$http
        .put(`${product}/${this.categoryId}`, param)
        .then((r) => {
          this.$mHelper.toast("编辑成功");
          this.$mRouter.back();
        })
        .catch(() => {});
    },
    //发布商品
    async releaseCommodities() {
      let param = this.getParams(this.products);
      await this.$http
        .post(product, param)
        .then((r) => {
          this.$mHelper.toast("发布成功");
          this.$mRouter.back();
        })
        .catch(() => {});
    },
    // 跳转至商品列表
    navTo(route) {
      this.$mRouter.push({ route });
    },
    // 数据初始化
    initData(id) {
      this.getCategoryDetail(id);
    },
    getCategoryDetail(id) {
      this.$http
        .get(`${product}/${id}`)
        .then((res) => {
          this.products.spec = res.data.spec;
          this.products.title = res.data.title;
          this.products.images = res.data.images;
          this.products.content_images = res.data.content_images;
          this.products.fist_category.id = res.data.category_id;
          this.firstList.forEach((item) => {
            if (item.id == this.products.fist_category.id) {
              this.products.fist_category.name = item.name;
            }
          });
          console.log(this.firstList);
          this.products.category_id = res.data.category_id;
          this.products.content = res.data.content;
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
page {
  background: #fff;
}
.commodities {
  border-top: 1px solid #eeeeee;
  height: 100vh;
  overflow: auto;
  background: #fff;
  .tit-text {
    font-size: 28upx;
    margin-right: 30upx;
    font-weight: 500;
  }
  .right-style {
    color: #999999;
  }
  .border-right {
    width: 18upx;
    height: 18upx;
    border-top: 2upx solid #999999;
    border-right: 2upx solid #999999;
    transform: rotate(45deg);
  }
  .row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1upx solid #eeeeee;
    margin: 0 30upx;
    height: 100upx;
    box-sizing: border-box;
    line-height: 100upx;
    .input {
      width: 220upx;
      font-size: 30upx;
      color: #303133;
    }
  }
  .split-border {
    height: 18upx;
    background: #f9f9f9;
  }
  .shop-detail {
    margin: 0 30upx;
    .shop-title {
      font-size: 28upx;
      margin: 30upx 0;
      font-weight: 500;
    }
    .textarea {
      height: 100upx;
    }
  }
  .border-bottom {
    border-bottom: 1px solid #eeeeee;
  }
  .image-box-wrappers {
    display: flex;
    justify-items: flex-start;
    flex-wrap: wrap;
    position: relative;
    padding: 30upx 0;
    margin: 0 30upx;
    .image-item {
      position: relative;
      .delete-img {
        position: absolute;
        top: 0px;
        z-index: 10;
        right: 15upx;
        width: 32upx;
        height: 32upx;
      }
      .image {
        width: 160upx;
        height: 160upx;
        margin-right: 30upx;
      }
      .images {
        width: 116upx;
        margin-right: 30upx;
        height: 116upx;
      }
    }
  }
  .portrait-box {
    clear: both;
    z-index: 20;
  }

  .portrait {
    position: relative;
    width: 160upx;
    height: 160upx;
    margin-left: 30upx;
  }
  .portraits {
    position: relative;
    width: 116upx;
    height: 116upx;
    margin-left: 30upx;
  }
}
</style>
